
import { InjectRepository } from '@nestjs/typeorm';
import { Repository ,Not ,In,Like} from 'typeorm';
import { Injectable } from '@nestjs/common';
import { ResultData } from 'src/common/utils/result';
import { CreateStudentDto, UpdateStudentDto, QueryStudentDto } from './dto/student.dto';
import { StudentEntity } from './entities/student.entity';

@Injectable()
export class StudentService {
constructor(
    @InjectRepository(StudentEntity)
    private readonly studentEntityRep: Repository<StudentEntity>,
) {}
    async create(createStudentDto: CreateStudentDto) {
        const res = await this.studentEntityRep.save(createStudentDto);
        return ResultData.ok(res);
    }

    // 数据处理函数
    private  returnFormatDate(data:StudentEntity[] | StudentEntity) {
        const getData = (value:StudentEntity)=>{
            const { classz, school, professional,campus, ...rest } = value;
            return {
                ...rest,
                schoolName: school?.schoolName,
                proName: professional?.proName,
                campusName: campus?.campusName,
                className: classz?.className,
            }
        }
       if(Array.isArray(data)){
           return  data.map(item=>getData(item))
       }else{
            return getData(data)
       }
    }

    async findAll(query :QueryStudentDto ) {
        const entity = this.studentEntityRep.createQueryBuilder('entity');
        entity.leftJoinAndSelect('entity.school', 'school')
        entity.leftJoinAndSelect('entity.campus', 'campus')
        entity.leftJoinAndSelect('entity.professional', 'professional')
        entity.leftJoinAndSelect('entity.classz', 'classz')

        entity.where({ delFlag: '0'});
        if(query.studentId){
          entity.andWhere("entity.studentId = :studentId", {studentId: query.studentId});
        }
        if(query.status){
              entity.andWhere("entity.status = :status", {status: query.status});
            }
        if(query.createBy){
              entity.andWhere("entity.createBy = :createBy", {createBy: query.createBy});
            }
        if(query.createTime){
              entity.andWhere("entity.createTime BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
            }
        if(query.updateBy){
              entity.andWhere("entity.updateBy = :updateBy", {updateBy: query.updateBy});
            }
        if(query.updateTime){
              entity.andWhere("entity.updateTime BETWEEN :start AND :end", { start: query.params.beginTime, end: query.params.endTime });
            }
        if(query.remark){
              entity.andWhere("entity.remark = :remark", {remark: query.remark});
            }
        if(query.studentNumber){
              entity.andWhere("entity.studentNumber = :studentNumber", {studentNumber: query.studentNumber});
            }
        if(query.oldName){
              entity.andWhere("entity.oldName LIKE :oldName", {oldName: `%${query.oldName}%`});
            }
        if(query.idCard){
              entity.andWhere("entity.idCard = :idCard", {idCard: query.idCard});
            }
        if(query.phone){
              entity.andWhere("entity.phone = :phone", {phone: query.phone});
            }
        if(query.schoolId){
              entity.andWhere("entity.schoolId = :schoolId", {schoolId: query.schoolId});
            }
        if(query.campusId){
              entity.andWhere("entity.campusId = :campusId", {campus: query.campusId});
            }
        if(query.birthday){
              entity.andWhere("entity.birthday = :birthday", {birthday: query.birthday});
            }
        if(query.cardAddress){
              entity.andWhere("entity.cardAddress = :cardAddress", {cardAddress: query.cardAddress});
            }
        if(query.houseAddress){
              entity.andWhere("entity.houseAddress = :houseAddress", {houseAddress: query.houseAddress});
            }
        if(query.emergency){
              entity.andWhere("entity.emergency = :emergency", {emergency: query.emergency});
            }
        if(query.state){
              entity.andWhere("entity.state = :state", {state: query.state});
            }
        if(query.gender){
              entity.andWhere("entity.gender = :gender", {gender: query.gender});
            }
	if(query.studentName){
          entity.andWhere("entity.studentName LIKE :studentName", {studentName: `%${query.studentName}%`});
        }
        if (query.orderByColumn && query.isAsc) {
          const key = query.isAsc === 'ascending' ? 'ASC' : 'DESC';
          entity.orderBy(`entity.${query.orderByColumn}`, key);
        }
        entity.skip(query.pageSize * (query.pageNum - 1)).take(query.pageSize);
        const [list, total] = await entity.getManyAndCount();

        return ResultData.ok({
            list:this.returnFormatDate(list),
            total,
        });
    }

    async findOne(id: number) {
        const res = await this.studentEntityRep.findOne({
            where: {
                delFlag: '0',
                studentId: id,
            },
        });
        return ResultData.ok(res);
    }

    async update(updateStudentDto: UpdateStudentDto) {
        const res = await this.studentEntityRep.update({  studentId: updateStudentDto.studentId }, updateStudentDto);
        return ResultData.ok({value:res.affected >= 1});
    }

    async remove(studentIds: number[]) {
        const res = await this.studentEntityRep.update(
            { studentId: In(studentIds) },
            {
                delFlag: '1',
            },
        );
        return ResultData.ok({value:res.affected >= 1});
    }
}
